import { JJUtil } from './../util/index.js'
import { CryptoJS } from './../thirdparty/index.js'
import APPConfig from './../resource/file/appConfig/JJAPPConfig.js'

let g_deviceNo = ''

export default class JJDeviceHelper {

    static getDeviceNo() {
        
        if (!JJUtil.isEmpty(g_deviceNo)) {
            return g_deviceNo;
        }
 
        const keyDecryptValue = 'JJDeviceHelper_deviceNo_key'
        let key = CryptoJS.MD5(keyDecryptValue).toString()
        if (APPConfig.isDebug) {
            key = keyDecryptValue
        }
        key  = key ? key : keyDecryptValue


        const storageDeviceNo = wx.getStorageSync(key)
        if (JJUtil.isNotNull(storageDeviceNo) && storageDeviceNo.length > 0) {
            g_deviceNo = storageDeviceNo
            return storageDeviceNo
        }

        let deviceNo = ''
        
        for (let i = 0; i < 50; ++i) {
            deviceNo = deviceNo + JJUtil.random(1, 100000).toString() + '_'
        }

        const dateStr = Date.now().toString()
        deviceNo = deviceNo + dateStr + '_'
        
        const systemInfo = wx.getSystemInfoSync()

        if (JJUtil.isNotNull(systemInfo.brand)) {
            deviceNo = deviceNo + systemInfo.brand + '_'
        }

        if (JJUtil.isNotNull(systemInfo.model)) {
            deviceNo = deviceNo + systemInfo.model + '_'
        }

        if (JJUtil.isNotNull(systemInfo.pixelRatio)) {
            deviceNo = deviceNo + systemInfo.pixelRatio.toString() + '_'
        }

        if (JJUtil.isNotNull(systemInfo.screenWidth)) {
            deviceNo = deviceNo + systemInfo.screenWidth.toString() + '_'
        }

        if (JJUtil.isNotNull(systemInfo.screenHeight)) {
            deviceNo = deviceNo + systemInfo.screenHeight.toString() + '_'
        }

        if (JJUtil.isNotNull(systemInfo.version)) {
            deviceNo = deviceNo + systemInfo.version + '_'
        }

        if (JJUtil.isNotNull(systemInfo.system)) {
            deviceNo = deviceNo + systemInfo.system + '_'
        }

        if (JJUtil.isNotNull(systemInfo.platform)) {
            deviceNo = deviceNo + systemInfo.platform + '_'
        }

        if (JJUtil.isNotNull(systemInfo.fontSizeSetting)) {
            deviceNo = deviceNo + systemInfo.fontSizeSetting.toString() + '_'
        }

        const md5DeviceNo = CryptoJS.MD5(deviceNo).toString()
        if (JJUtil.isNotNull(md5DeviceNo) && md5DeviceNo.length > 0) {
            deviceNo = md5DeviceNo
        }

        g_deviceNo = deviceNo
        if (!JJUtil.isEmpty(g_deviceNo)) {
            wx.setStorageSync(key, g_deviceNo)
        }
        
        return g_deviceNo
    }
}
